package com.example.yaseademo.utils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

public class SocketThread extends Thread {

    private Socket socket;
    private Client client;
    private String ip;
    private int port;
    private boolean isStart = false;
    private MessageListener mMessageListener;

    /**
     * 使用TCP协议,连接访问
     *
     * @param ip               目标机器的IP
     * @param port             端口
     * @param mMessageListener 收到服务器端数据时将回调该接口内的
     */
    public SocketThread( String ip, int port,
                        MessageListener mMessageListener) {
        this.ip = ip;
        this.port = port;
        this.mMessageListener = mMessageListener;
    }

    public void run() {
        try {
            //实例化一个Socket对象
            socket = new Socket();
            //与对应的ip、端口进行连接,先要把桥建好
            socket.connect(new InetSocketAddress(ip, port), 3000);
            if (socket.isConnected()) {
                System.out.println("Connected..");
                client = new Client(socket, mMessageListener);
                //打开对应的输入/输出流监听
                client.start();
                isStart = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
            isStart = false;
        }
    }

    // 直接通过client得到读线程
    public ClientInputThread getClientInputThread() {
        return client.getIn();
    }

    // 直接通过client得到写线程
    public ClientOutputThread getClientOutputThread() {
        return client.getOut();
    }

    //返回Socket状态
    public boolean isStart() {
        return isStart;
    }

    // 直接通过client停止读写消息
    public void setIsStart(boolean isStart) {
        this.isStart = isStart;
        client.getIn().setStart(isStart);
        client.getOut().setStart(isStart);
    }

    //发送消息
    public void sendMsg(String msg) {
        client.getOut().sendMsg(msg);
    }

    public class Client {

        private ClientInputThread in;
        private ClientOutputThread out;

        public Client(Socket socket, MessageListener mMessageListener) {
            //用这个监听输入流线程来接收信息
            in = new ClientInputThread(socket);
            in.setMessageListener(mMessageListener);
            //以后就用这个监听输出流的线程来发送信息了
            out = new ClientOutputThread(socket);
        }

        public void start() {
            in.setStart(true);
            out.setStart(true);
            in.start();
            out.start();
        }

        // 得到读消息线程
        public ClientInputThread getIn() {
            return in;
        }

        // 得到写消息线程
        public ClientOutputThread getOut() {
            return out;
        }
    }
}